package com.alibaba.csp.sentinel.demo.zuul.gateway.sentinel;

import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.BlockResponse;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.DefaultBlockFallbackProvider;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.BlockException;

/**
 * @author gaozq
 */
public class MyBlockFallbackProvider extends DefaultBlockFallbackProvider {

    /**
     * 在 SentinelZuulPreFilter 的run方法中如果抛出异常，就把异常信息写入到 HttpServletResponse
     *    ZuulBlockFallbackProvider zuulBlockFallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(
     *                 fallBackRoute);
     *             BlockResponse blockResponse = zuulBlockFallbackProvider.fallbackResponse(fallBackRoute, ex);
     *             // Prevent routing from running
     *             ctx.setRouteHost(null);
     *             ctx.set(ZuulConstant.SERVICE_ID_KEY, null);
     *
     *             // Set fallback response.
     *             ctx.setResponseBody(blockResponse.toString());
     *             ctx.setResponseStatusCode(blockResponse.getCode());
     *             // Set Response ContentType
     *             ctx.getResponse().setContentType("application/json; charset=utf-8");
     */
    @Override
    public BlockResponse fallbackResponse(String route, Throwable cause) {
        RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route));
        if (cause instanceof BlockException) {
            return new BlockResponse(429, "Sentinel block exception", route);
        } else {
            return new BlockResponse(500, "System Error", route);
        }

//        throw new RuntimeException("访问频率测试，请勿频繁点击，如有问题联系技术人员！");
    }
}
